package com.hww.bean;


import com.hww.service.UserService;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author: heweiwei
 * @time: 2025/4/28 20:29
 * @description:
 */
public class MyBeanPostProcessor implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) {
        System.out.println("Before initialization for bean: " + beanName);
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) {
        System.out.println("After initialization for bean: " + beanName);
        if (bean instanceof UserService) {
            return Proxy.newProxyInstance(
                    bean.getClass().getClassLoader(),
                    bean.getClass().getInterfaces(),
                    new InvocationHandler() {
                        @Override
                        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                            if ("sayHello".equals(method.getName())) {
                                System.out.println("Before sayHello method call");
                                Object result = method.invoke(bean, args);
                                System.out.println("After sayHello method call");
                                return result;
                            }
                            return method.invoke(bean, args);
                        }
                    }
            );
        }
        return bean;
    }
}
